<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\YuanfenjuService;

/**
 * 老黄历接口
 * @ApiWeigh (95)
 */
class Laohuangli extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    /**
     * 查询老黄历
     * 
     * @ApiTitle    (查询老黄历)
     * @ApiSummary  (根据日期查询老黄历信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/laohuangli/index)
     * 
     * @ApiParams   (name="title_laohuangli", type="string", required=true, description="年月日，格式：YYYY-MM-DD")
     * 
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": {
          "yangli": "1988-02-20",           // 阳历
          "yinli": "一九八八年正月初四(农历)", // 阴历
          "wuxing": "大林木(年) 大溪水(月) 壁灯火(日)", // 五行纳音
          "chongsha": "冲(己巳)蛇煞东",      // 冲煞
          "baiji": "宜:结婚 订婚 开市 安床", // 百忌
          "jishen": "天德 月德 天马",        // 吉神宜趋
          "yi": "祭祀 祈福 求嗣 开光",       // 宜
          "xiongshen": "月煞 月虚 四击",     // 凶神宜忌
          "ji": "动土 破土 安葬 开生坟"      // 忌
        }
      })
     */
    public function index()
    {
        $date = $this->request->post('title_laohuangli');
        
        // 参数验证
        if (empty($date)) {
            $this->error(__('Parameter title_laohuangli can not be empty'));
        }
        
        // 验证日期格式
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            $this->error(__('Invalid date format, should be YYYY-MM-DD'));
        }
        
        // 验证日期有效性
        $timestamp = strtotime($date);
        if ($timestamp === false || $timestamp < strtotime('1900-01-01') || $timestamp > strtotime('2099-12-31')) {
            $this->error(__('Invalid date value, should be between 1900-01-01 and 2099-12-31'));
        }

        try {
            // 查询日志记录
            $cache = \app\common\model\LaohliLog::where('query_date', $date)->find();
            if($cache) {
                $this->success('获取成功', json_decode($cache['data'], true));
            }

            $result = YuanfenjuService::instance()->request('/Gongju/laohuangli', [
                'title_laohuangli' => $date
            ]);
            
            if ($result['errcode'] != 0) {
                $this->error($result['errmsg'] ?? '老黄历查询失败');
            }
            
            // 记录查询日志
            \app\common\model\LaohliLog::create([
                'query_date' => $date,
                'data' => json_encode($result['data']),
                'createtime' => time()
            ]);
            
            $this->success('获取成功', $result['data']);
            
        } catch (\think\exception\PDOException $e) {
            $this->error('服务异常：' . $e->getMessage());
        }
    }
}